package com.carbon.account.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.carbon.account.service.EmailService;
import com.carbon.account.utils.StringHandleUtils;
import com.carbon.common.exception.CommonBizException;
import com.carbon.common.redis.RedisService;
import com.carbon.domain.common.ApiResult;
import com.carbon.domain.common.constant.EmailConstant;
import com.carbon.domain.common.constant.RedisKeyName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * [一句话描述该类的功能]
 *
 * @author : [Lenovo]
 * @version : [v1.0]
 * @createTime : [2024/8/17 下午3:09]
 */
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {
    @Value("${mail.username}")
    private String sender;
    @Resource
    private JavaMailSender jms;
    @Resource
    private RedisService redisService;

    @Override
    public String sendHtml(String sender, String receiver, String subject, String content) {
        MimeMessage message = jms.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //发送方
            helper.setFrom(sender);
            //接收方
            helper.setTo(receiver);
            //邮件主题
            helper.setSubject(subject);
            //邮件内容
            helper.setText(content, true);
            jms.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return "邮件发送成功，请查收邮件！";
    }

    @Override
    public void checkValidateCode(String email, String code,String type) {
        if (StrUtil.isEmpty(email) || StrUtil.isEmpty(code)) {
            throw new CommonBizException("邮箱或验证码为空");
        }
        String redisKey = type + email;
        String redisMsgCode = redisService.get(redisKey);
        log.info("redisMsgCode：{}",redisMsgCode);
        if (StrUtil.isEmpty(redisMsgCode)) {
            throw new CommonBizException("验证码已过期");
        }
        if (!code.equals(redisMsgCode)) {
            throw new CommonBizException("请输入正确的验证码");
        }
        //验证码消费后失效
        redisService.delete(CollUtil.newArrayList(redisKey));
    }
    public void sendRegisterCode(String email) {
        String key = RedisKeyName.EM_REGISTER_KEY + email;
        String validCode = StringHandleUtils.getRandomString(6);
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", validCode);
        //邮件内容
        String content = "<html>\n" +
                "<body>\n" +
                "尊敬的用户：" +
                "<h2>这是一封用户注册邮件,请使用下方验证码（区分大小写）进行注册!</h2>\n" +
                "<p>提示：验证码有效时间15分钟。</p>" +
                "<p style=\"background-color: #000000;color: #ffffff;font-size: 50px;width: 300px;height: 120px;line-height: 120px;text-align: center;\">" +
                validCode +
                "</p>"+
                "<p>注意：如果该邮件不是您操作发送，请忽视该邮件。</p>" +
                "</body>\n" +
                "</html>";
        redisService.setEx(key, validCode, 60, TimeUnit.SECONDS);
        sendHtml(sender,email, EmailConstant.ACCOUNT_REGISTER,content);
    }
    @Override
    public void sendForgotPasswordCode(String email) {
        String key = RedisKeyName.EM_FORGOT_PASSWORD_KEY + email;
        String validCode = StringHandleUtils.getRandomString(6);;
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", validCode);
        //邮件内容
        String content = "<html>\n" +
                "<body>\n" +
                "尊敬的用户：" +
                "<h2>这是一封密码找回邮件,请使用下方验证码（区分大小写）重置登录密码!</h2>\n" +
                "<p>提示：验证码有效时间15分钟。</p>" +
                "<p style=\"background-color: #000000;color: #ffffff;font-size: 50px;width: 300px;height: 120px;line-height: 120px;text-align: center;\">" +
                validCode +
                "</p>"+
                "<p>注意：如果该邮件不是您操作发送，请忽视该邮件。</p>" +
                "</body>\n" +
                "</html>";
        redisService.setEx(key, validCode, 60000, TimeUnit.SECONDS);
        sendHtml(sender,email, EmailConstant.ACCOUNT_REGISTER,content);
    }

}
